package com.example.spider.provider.why10w;

import com.example.spider.provider.why10w.dto.Why10wDetailTask;
import com.example.spider.provider.why10w.persistent.Why10wRepository;
import com.example.spider.task.SpiderResultHandler;
import com.example.spider.task.Task;
import lombok.extern.slf4j.Slf4j;
import org.shoulder.core.exception.CommonErrorCodeEnum;
import org.shoulder.core.util.AssertUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 处理列表查询结果
 *
 * @author lym
 */
@Slf4j
public abstract class AbstractWhy10wDetailResultHandler implements SpiderResultHandler<Why10wDetailTask, String> {

    @Autowired
    protected Why10wRepository repository;

    protected final String source;

    protected AbstractWhy10wDetailResultHandler() {
        String fullName = getClass().getName();
        String pkgName = AbstractWhy10wDetailResultHandler.class.getName()
                .replace(AbstractWhy10wDetailResultHandler.class.getSimpleName(), "");
        AssertUtils.isTrue(fullName.contains(pkgName), CommonErrorCodeEnum.CODING);
        String resultName = fullName.replace(pkgName, "");
        int lastDot = resultName.lastIndexOf('.');
        this.source = resultName.substring(0, lastDot);
    }
    protected AbstractWhy10wDetailResultHandler(String source) {
        this.source = source;
    }

    @Override
    public <R> boolean canHandle(Task<R> task, R result) {
        return task instanceof Why10wDetailTask && source.equals(((Why10wDetailTask) task).getSource());
    }

    /**
     * 处理结果
     *
     * @param result 页面信息
     */
    public void handle(Why10wDetailTask task, String result) {
        log.debug("prepare handing {}: {}", source, task.getUrl());
        try {
            doHandle(task, result);
            log.info("handle finished {}: {}", source, task.getUrl());
        } catch (Exception e) {
            log.error("Fail process {}: {}", source, task.getUrl(), e);
        }
    }

    // 判断本次爬取是否有效，无效跳过

    // 缓存爬取结果

    // 解析为标准 DTO

    // 保存
    protected abstract void doHandle(Why10wDetailTask task, String result);

}
